package org.handyc.game.event;

import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

public class GameKeyListener implements java.awt.event.KeyListener {

	public static void main(String... args) {
		ArrayList<Integer[]> list = new ArrayList<Integer[]>();
		Integer[] a = new Integer[] { 3, 4 };
		Integer[] b = new Integer[] { 3, 5, 6 };
		Integer[] c = new Integer[] { 2, 3 };
		list.add(a);
		list.add(b);
		list.add(c);
		System.out.println(a);
		System.out.println(b);
		System.out.println(c);

		System.out.println(list);
	}

	public void addKeyListener(KeyListener keyListener, Integer... keyCodes) {
		// 排序
		Arrays.sort(keyCodes);

		for (int keycode : keyCodes) {
			if (!keyMap.containsKey(keycode)) {
				keyMap.put(keycode, new ArrayList<Integer[]>());
			}
			keyMap.get(keycode).add(keyCodes);
			// 按组合键个数排序
			Collections.sort(keyMap.get(keycode), new Comparator<Integer[]>() {
				public int compare(Integer[] o1, Integer[] o2) {
					if (o1.length < o2.length) {
						return 1;
					} else if (o1.length > o2.length) {
						return -1;
					}
					return 0;
				}
			});
		}
		listenerMap.put(keyCodes, keyListener);
	}

	private Map<Integer, ArrayList<Integer[]>> keyMap = new HashMap<Integer, ArrayList<Integer[]>>();

	private Map<Integer[], KeyListener> listenerMap = new HashMap<Integer[], KeyListener>();

	// 正按下的键
	private HashSet<Integer> pressedKeys = new HashSet<Integer>();

	public void keyTyped(KeyEvent e) {
		// System.out.println("keyTyped");
	}

	public void keyPressed(KeyEvent e) {
		int keyCode = e.getKeyCode();
		this.pressedKeys.add(keyCode);
		// System.out.println(e.getModifiers());
		trigger(keyCode, new HashSet<Integer>(pressedKeys));
	}

	public void keyReleased(KeyEvent e) {
		// int会按序号删除
		pressedKeys.remove((Integer) e.getKeyCode());
	}

	public void trigger(Integer keyCode, HashSet<Integer> pressedKeys) {
		// System.out.println(pressedKeys);
		if (keyMap.containsKey(keyCode)) {
			List<Integer[]> keyList = keyMap.get(keyCode);
			for (Integer[] keys : keyList) {
				boolean flag = true;
				for (Integer key : keys) {
					if (!pressedKeys.contains(key)) {
						flag = false;
						break;
					}
				}
				if (flag) {
					for (Integer key : keys) {
						pressedKeys.remove(key);
					}
					listenerMap.get(keys).onTrigger();
					break;
				}
			}
		} else {
			pressedKeys.remove(keyCode);
		}
		if (!pressedKeys.isEmpty()) {
			trigger(pressedKeys.iterator().next(), pressedKeys);
		}
	}
}
